package com.jl.rule;

import com.jl.JLDataTime;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDateTime;
import java.util.Collection;

/**
 * 规则 hashcode取余
 *
 * @param <T>
 */
public class JLRuleHashCodeRem<T extends Comparable<?>> implements PreciseShardingAlgorithm<T>, RangeShardingAlgorithm<T> {

    private String length;

    public JLRuleHashCodeRem(String length) {
        this.length = length;
    }

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<T> preciseShardingValue) {
        T v = preciseShardingValue.getValue();
        if (v instanceof LocalDateTime) {
            v = (T) JLDataTime.toString((LocalDateTime) v);
        }
        int lengths = Integer.parseInt(length);
        for (String each : collection) {
            if (each.endsWith(Integer.toString(Math.abs(v.hashCode()) % lengths))) {
                return each;
            }
        }
        return null;
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<T> rangeShardingValue) {
        return collection;
    }
}
